package robocup.connection;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;

/**
 * This class is used to buffer data, which is send and received when
 * communicating with the soccer server. Since the data is always passed as
 * string, this class provides the corresponding methods for setting and getting
 * these.
 */
public class ByteBuffer
    extends ByteArrayOutputStream {

  /**
   * A class that is capable of storing data
   * 
   * @param size -
   *          the size of the buffer
   */
  public ByteBuffer(
      final int size) {

    super(size);
  }

  /**
   * @return returns the buffer-array.
   */
  public byte[] getByteArray() {

    return this.buf;
  }

  /**
   * This methdo sets a string into the buffer.
   * 
   * @param str -
   *          the string to set.
   * @throws IOException
   */
  public synchronized void setString(final String str) throws IOException {

    super.write(str.getBytes());
  }

  /**
   * @return string containing the buffered data.
   * @throws IOException
   */
  public String getString() throws IOException {

    final ByteArrayInputStream in = new ByteArrayInputStream(this.buf);
    int c;
    final StringWriter w = new StringWriter();
    while (((c = in.read()) != 0) && (c != -1)) {
      w.write((char) c);
    }
    return w.getBuffer().toString();
  }

  /**
   * @return The length of the buffer-array.
   */
  public int length() {

    return this.buf.length;
  }

  /**
   * Resets all values of the buffer-array to zero.
   */
  @Override
  public void reset() {

    super.reset();

    for (int i = 0; i < this.buf.length; i++) {
      this.write(0);
    }
    super.reset();
  }
}
